package cn.klaw.event;

import cn.klaw.consts.ProjectEventConst;
import cn.klaw.module.ProjectEvent;

import java.util.*;
import java.util.function.Consumer;

/**
 * 自定义事件注册
 */
public class ProjectEventHolder {

    private ProjectEventHolder() {
    }

    /**
     * {topic:{keymatcher:consumer}}
     */
    private static final Map<String, Map<ProjectEventKeyMatcher, Consumer<ProjectEvent>>> events = new HashMap<>();

    /**
     * 添加事件处理器, 默认主题
     */
    public static void addEventListener(ProjectEventKeyMatcher keyMatcher, Consumer<ProjectEvent> consumer) {
        addEventListener(ProjectEventConst.DEFAULT_TOPIC_NAME, keyMatcher, consumer);
    }

    /**
     * 添加事件处理器
     */
    public static void addEventListener(String topic, ProjectEventKeyMatcher keyMatcher, Consumer<ProjectEvent> consumer) {
        Map<ProjectEventKeyMatcher, Consumer<ProjectEvent>> topicEvents = events.computeIfAbsent(topic, k -> new HashMap<>());
        topicEvents.put(keyMatcher, consumer);
    }

    /**
     * 获取事件匹配的处理器, 默认主题
     */
    public static List<Consumer<ProjectEvent>> getEventListener(ProjectEvent event) {
        return getEventListener(ProjectEventConst.DEFAULT_TOPIC_NAME, event);
    }

    /**
     * 获取事件匹配的处理器
     */
    public static List<Consumer<ProjectEvent>> getEventListener(String topic, ProjectEvent event) {
        Map<ProjectEventKeyMatcher, Consumer<ProjectEvent>> topicEvents = events.getOrDefault(topic, Collections.emptyMap());
        List<Consumer<ProjectEvent>> consumers = new ArrayList<>();
        for (Map.Entry<ProjectEventKeyMatcher, Consumer<ProjectEvent>> entry : topicEvents.entrySet()) {
            if(entry.getKey().isMatch(event)){
                consumers.add(entry.getValue());
            }
        }
        return consumers;
    }
}
